package com.xiashitech.agent.utils;

import com.xiashitech.agent.config.StartConfig;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.stream.Collectors;

public class ClassLoaderUtil {
    /**
     * 执行被当前线程类加载器加载的类的方法
     * @param className
     * @param methodName
     * @param param
     * @return Object
     */
    public static Object invoke(String className, String methodName, Object... param) {
        Object returnObj = null;
        try {
            if(className == null || methodName == null) {
                throw new IllegalArgumentException("ClassLoaderUtil.invoke:className or methodName is null!");
            }
            Class invokedClass = Thread.currentThread().getContextClassLoader().loadClass(className);
            Method method;
            if(param == null || "".equals(param) || param.length == 0) {
                method = invokedClass.getMethod(methodName);
            } else {
                method = invokedClass.getMethod(methodName,Arrays.stream(param).map(paramObj -> paramObj.getClass()).toArray(Class[]::new));
            }
            if(Modifier.isStatic(method.getModifiers())) {
                returnObj = method.invoke(null,param);
            } else {
                returnObj = method.invoke(invokedClass.newInstance(),param);
            }
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return returnObj;
    }
}
